package top.chenyaohua.asm;

import org.objectweb.asm.AnnotationVisitor;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class CustomFieldVisitor extends FieldVisitor {

    private FieldMetadata fieldMetadata;

    private CustomClassVisit customClassVisit;

    public CustomFieldVisitor (FieldVisitor fv,CustomClassVisit customClassVisit) {
        super(Opcodes.ASM5, fv);
        this.customClassVisit = customClassVisit;
        List<FieldMetadata> fieldMetadata = customClassVisit.getBeanMetadata().getFieldMetadata();
        this.fieldMetadata =  fieldMetadata.get(fieldMetadata.size() - 1);
    }

    @Override
    public AnnotationVisitor visitAnnotation (String desc, boolean visible) {

        AnnotationMetadata annotationMetadata = new AnnotationMetadata(desc);
        List<AnnotationMetadata> anns = Optional.ofNullable(fieldMetadata.getAnnotations()).orElseGet(ArrayList::new);
        anns.add(annotationMetadata);
        this.fieldMetadata.setAnnotations(anns);

        return new CustomAnnotationVisitor( super.visitAnnotation(desc, visible) ,customClassVisit,this,null);
    }

    public CustomClassVisit getCustomClassVisit () {
        return customClassVisit;
    }

    public FieldMetadata getFieldMetadata () {
        return fieldMetadata;
    }
}
